import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:trip_flutter/util/screen_adapt_helper.dart';

class Slidewidget extends StatefulWidget {
  final List<String> bannerList;
  const Slidewidget({super.key, required this.bannerList});
  @override
  State<Slidewidget> createState() => _SlidewidgetState();
}

class _SlidewidgetState extends State<Slidewidget> {
  final CarouselSliderController _controller = CarouselSliderController();
  int currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Stack(
      children: [
        CarouselSlider(
          items: widget.bannerList.map((item) => Item(item, width)).toList(),
          carouselController: _controller,
          options: CarouselOptions(
            height: 160.px,
            autoPlay: true,
            viewportFraction: 1.0,
            onPageChanged: (int index, CarouselPageChangedReason reason) => {
              setState(() {
                currentIndex = index;
              }),
            },
          ),
        ),
        Positioned(bottom: 10.px, left: 0, right: 0, child: _indicator()),
      ],
    );
  }

  Widget Item(String item, double width) {
    return GestureDetector(
      onTap: () => {
        //实现一个路由跳转
      },
      //请求网络上的数据然后转化为图像
      child: Image.asset(item, fit: BoxFit.cover, width: width),
    );
  }

  //指示器代码
  _indicator() {
    return Row(
      //设置主方向的居中
      mainAxisAlignment: MainAxisAlignment.center,
      children: widget.bannerList.asMap().entries.map((entry) {
        return GestureDetector(
          onTap: () => _controller.animateToPage(entry.key),
          child: Container(
            padding: EdgeInsets.all(5),
            height: 6.px,
            width: 6.px,
            margin: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.white.withOpacity(
                currentIndex == entry.key ? 0.9 : 0.4,
              ),
            ),
          ),
        );
      }).toList(),
    );
  }
}
